package cn.wolfcode.trip.core.service.impl;

import cn.wolfcode.trip.core.domain.User;
import cn.wolfcode.trip.core.mapper.UserMapper;
import cn.wolfcode.trip.core.query.QueryObject;
import cn.wolfcode.trip.core.service.IUserService;
import cn.wolfcode.trip.core.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    // 验证登录方法
    public User login(User user) {
        if(!(StringUtils.hasLength(user.getEmail())&&StringUtils.hasLength(user.getPassword()))){
            throw new RuntimeException("亲,邮箱或密码不能为空");
        }
        User temp = userMapper.selectByEmailAndPassword(user.getEmail(), user.getPassword());
        if(temp==null){
            throw new RuntimeException("亲,邮箱或密码错误!");
        }
        //登陆成功
        UserContext.setCurrentUser(temp);
        return temp;
    }

    // 注册方法
    public void register(User user) {
        if(!(StringUtils.hasLength(user.getEmail())&&StringUtils.hasLength(user.getPassword()))){
            throw new RuntimeException("亲,邮箱或密码不能为空");
        }
        //获取邮箱,检查是否已被注册
        User temp = userMapper.selectByEmailAndPassword(user.getEmail(), null);
        if(temp!=null){
            throw new RuntimeException("亲,邮箱已被注册");
        }
        user.setHeadImgUrl("/img/user/head.jpg");//头像
        user.setCoverImgUrl("/img/user/bg.jpeg");//封面
        userMapper.insert(user);
    }

    public PageInfo<User> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    public User getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }


}
